package com.wondersgroup.wx;

import net.sf.json.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class OpenIdUtil {

  /**
   * 正式 环境 APPID
    <!--公众号ID-->
   <add key="appId" value="wx24c55f38b535cd96" />
    <!--公众号密钥-->
   <add key="secret" value="2f0e3137cee960b6ad9750430e83c38d" />
   */

  public  static String  APPID = "wx4f38e1e331944941";
  public  static String  APPSECRET = "e11f1b6ee6934741d3aa2f1c30bbb13f";
  public  static String  GETOPENID = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

  /*通过code获取用户openid*/
  public static JSONObject getOpenid(String code) throws IOException {
    JSONObject jsonObject = null;
    String path = GETOPENID.replace("APPID", APPID).replace("SECRET", APPSECRET).replace("CODE", code);
    StringBuffer buffer = new StringBuffer();
    URL url = new URL(path);
    HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
    httpUrlConn.setRequestMethod("POST");
    httpUrlConn.setDoOutput(true);
    httpUrlConn.setDoInput(true);
    httpUrlConn.setUseCaches(false);
    // 将返回的输入流转换成字符串
    InputStream inputStream = httpUrlConn.getInputStream();
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    String str = null;
    while ((str = bufferedReader.readLine()) != null) {
      buffer.append(str);
    }
    bufferedReader.close();
    inputStreamReader.close();
    // 释放资源
    inputStream.close();
    inputStream = null;
    httpUrlConn.disconnect();
    jsonObject = JSONObject.fromObject(buffer.toString());
    return jsonObject;
  }

}
